package com.xiumu.common.redis;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

/**
 * redis 工具类
 *
 * @Author XiuMu
 * @Date 2023/5/31 16:27
 **/
public class RedisService {

    private final RedisTemplate redisTemplate;


    public RedisService(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取缓存的对象
     *
     * @param key 键值
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 获取缓存的对象并删除
     *
     * @param key 键值
     */
    public <T> T getCacheObjectAndDelete(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.getAndDelete(key);
    }

    /**
     * 缓存到 redis 并设置过期时间
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间单位
     */
    public <T> void setCacheObject(String key, T value, int timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 缓存到 redis 并设置过期时间是多少秒
     *
     * @param key     缓存的键值
     * @param value   缓存的值
     * @param seconds 时间, 单位是秒
     */
    public <T> void setCacheObject(String key, T value, int seconds) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
    }

    /**
     * 缓存到 redis 且永不过期
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(String key, T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 删除某个缓存对象
     *
     * @param key 键值
     */
    public Boolean deleteObject(String key) {
        return redisTemplate.delete(key);
    }

}
